package com.yjd.api.recharge;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.bank.model.BankInfoModel;
import com.yjd.comm.bank.model.BankModel;
import com.yjd.comm.bank.service.IBankInfoService;
import com.yjd.comm.bank.service.IBankService;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.funds.dto.QuickPayDTO;
import com.yjd.comm.funds.dto.RechOrderDTO;
import com.yjd.comm.funds.enums.RechChannel;
import com.yjd.comm.funds.enums.RechSourceEnum;
import com.yjd.comm.funds.enums.RechTypeEnum;
import com.yjd.comm.funds.model.RechargeOrderModel;
import com.yjd.comm.funds.service.IRechargeOrderService;
import com.yjd.comm.order.service.IOrderService;
import com.yjd.comm.repayment.service.IRepaymentDataService;
import com.yjd.comm.user.service.IUserDataService;
import com.yjd.comm.user.util.UserUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.QuickPayUtils;
import com.yjd.comm.util.ServletUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yjd-wap on 2017/9/19.
 */
@Controller
@Scope("prototype")
@RequestMapping("/recharge/")
public class RechargeControl extends BaseControl {

    @Resource
    private IUserDataService userDataService;

    @Resource
    private IBankService bankService;

    @Resource
    private IBankInfoService bankInfoService;

    @Resource
    private IRechargeOrderService rechargeOrderService;

    @Resource
    private IOrderService orderService;

    @Resource
    private IRepaymentDataService repaymentDataService;

    /**
     * 充值预处理接口，判断当前用户是否绑定银行卡
     *
     * @throws Exception
     */
    @RequestMapping(value = "pre", method = RequestMethod.POST)
    public void pretreatment() throws Exception {
        Map resultMap = new HashMap();
        resultMap.put("bankFlag", 0);

        BankModel bankModel = bankService.getModelById(super.getSessionUserId(), DbWREnums.WRITE);
        if (bankModel != null) {
            resultMap.put("bank_img", getBankImage(bankModel.getBank_id()+""));
            resultMap.put("bankFlag", 1);
            resultMap.put("bank_no", UserUtil.disposeBankCardNo(bankModel.getBank_card_number()));
            resultMap.put("bank_name", bankModel.getBank_name());
        }
        this.successData(resultMap);
    }

    @RequestMapping(value = "payment")
    public String payment(Double price, Integer source, Integer type, Long ref_id) throws Exception {
        if (price == null || price < 0.01) {
            FrameUtil.throwBaseException1("请输入合法的金额");
        }
        RechTypeEnum rechTypeEnum = RechTypeEnum.parse(type);
        RechSourceEnum rechSourceEnum = RechSourceEnum.parse(source);
        if (rechSourceEnum == null) {
            rechSourceEnum = RechSourceEnum.UNKNOWN;
        }
        if (rechTypeEnum == null) {
            rechTypeEnum = RechTypeEnum.UNKNOWN;
        }
        BankModel bankModel = bankService.getModelById(super.getSessionUserId(), DbWREnums.WRITE);
        if (bankModel == null) {
            FrameUtil.throwBaseException1("请先绑定您的银行卡");
        }
        request.setAttribute("quickOrder", generateorder(price, rechSourceEnum, rechTypeEnum, bankModel, ref_id));
        return "recharge/quickwaiting";
    }


    /**
     * 充值 生成数据库订单及第三方订单信息
     */
    private QuickPayDTO generateorder(Double price, RechSourceEnum rechSourceEnum, RechTypeEnum rechTypeEnum, BankModel bankModel, Long ref_id) throws Exception {
        RechOrderDTO rechargeOrder = new RechOrderDTO();
        rechargeOrder.setId_bank(bankModel.getBank_id()); // 银行id
        rechargeOrder.setMpNumber(bankModel.getBank_mobile().toString());
        String transIp = ServletUtil.getIpAddr(request); // 当前用户的ip
        rechargeOrder.setUser_id(bankModel.getUser_id());
        rechargeOrder.setRealName(bankModel.getId_name());
        rechargeOrder.setCertNo(bankModel.getId_number());
        rechargeOrder.setPrice(price); // 充值金额
        rechargeOrder.setOrder_source(rechSourceEnum.getCode());
        rechargeOrder.setBank_no(bankModel.getBank_card_number());
        rechargeOrder.setOrder_type(rechTypeEnum.getCode());
        rechargeOrder.setTransIp(transIp);
        rechargeOrder.setRef_id(ref_id);
        RechChannel rechChannel = RechSourceEnum.ANDROID.getCode()==rechSourceEnum.getCode()?RechChannel.ANDROID:RechChannel.IOS;
        rechargeOrder.setRechChannel(rechChannel);
        return rechargeOrderService.rech(rechargeOrder);
    }

    @RequestMapping("pageUrl")
    public String pageUrl() throws Exception {
        return "recharge/transfinish";
    }

    /**
     * 支付后台回调（银行处理订单完成之后的回调）
     *
     * @return String
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("callback")
    public String callBack(@RequestParam("app_msg") String app_msg) throws Exception {
        Map<String, Object> rechargeResultMap = QuickPayUtils.resultMap(app_msg);
        if (!QuickPayUtils.validateResult(rechargeResultMap)) {
            FrameUtil.throwBaseException1("非法请求");
        }
        // 更新订单，并记录流水
        QuickPayDTO quickPayDTO = QuickPayUtils.parseOrder(rechargeResultMap);
        //将用户资金入账
        rechargeOrderService.callBack(quickPayDTO);
        // 本地充值订单是否存在
        RechargeOrderModel rechOrder = rechargeOrderService.getModelById(quickPayDTO.getSysOrderId(), DbWREnums.READ);
        //根据订单类型处理相应的结果
        // 资金先入账到用户的账户中，再进行相关业务操作避免第三方多次通知
        try {
            if (RechTypeEnum.PAYMENTS.getCode() == rechOrder.getOrder_type().intValue()) {
                //首付充值成功后，处理订单相关状态及扣款
                orderService.firstPaymentSuccess(rechOrder.getRef_id());
            } else if (RechTypeEnum.REPAYMENT.getCode() == rechOrder.getOrder_type().intValue()) {
                //还款充值成功后，处理还款报表及扣款
                repaymentDataService.repayment(rechOrder.getRef_id());
            }
        } catch (Exception e) {
            logger.error("充值回调处理成功，业务处理失败，订单信息：" + JSON.toJSONString(quickPayDTO) + "错误信息：" + e);
        }
        return "OK";
    }

    private String getBankImage(String bank_id) throws Exception {
        if(!bankImageCache.containsKey(bank_id)){
            BankInfoModel bifm = bankInfoService.getModelById(Long.valueOf(bank_id), DbWREnums.READ);
            bankImageCache.put(bank_id, bifm.getBank_code());
        }

        return ServletUtil.getFileUrl(ReferenceTypeEnum.BANK_PICTURE.getPath() + bankImageCache.get(bank_id) + ".png");
    }
    private static final Map<String, String> bankImageCache = new HashMap<String, String>();

}
